<template>
  <div class="app-container">
    <el-container>
      <el-header class="filter-container">
        <!--        <el-input v-model="input_toolbar" placeholder="请输入用户名" style="width: 200px; " class="filter-item"></el-input>-->
        <!--        <el-select v-model="tempOrganize" placeholder="组织架构" class="filter-item">-->
        <!--          <el-option-->
        <!--            v-for="item in organizeList"-->
        <!--            :key="item.id"-->
        <!--            :label="item.label"-->
        <!--            :value="item.id">-->
        <!--          </el-option>-->
        <!--        </el-select>-->

        <!--        <el-button type="primary" icon="el-icon-search" @click="onSearch" style="width: 90px;" class="filter-item">搜索-->
        <!--        </el-button>-->
        <el-button type="primary" icon="el-icon-plus" @click="onCreate(0)" class="filter-item">创建班级</el-button>
      </el-header>
      <el-main>
        <el-table :data="temperList" style="width: 100%;" border
                  :header-cell-style="{background:'#e1e4e5',color:'#80878f'}">
          <el-table-column align="center" label="ID" width="120">
            <template slot-scope="scope">
              {{ scope.row.id }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="年级" width="120">
            <template slot-scope="scope">
              {{ scope.row.name }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="年级编码" width="120">
            <template slot-scope="scope">
              {{ scope.row.kcode }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="学生数量" width="120">
            <template slot-scope="scope">
              {{ scope.row.classnum }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="组织结构" width="120">
            <template slot-scope="scope">
              {{ scope.row.organize_code }}
            </template>
          </el-table-column>
          <el-table-column align="header-center" label="描述">
            <template slot-scope="scope">
              {{ scope.row.description }}
            </template>
          </el-table-column>
          <el-table-column align="center" label=操作>
            <template slot-scope="scope">
              <el-button type="primary" size="small" @click="handleEdit(scope)">编辑</el-button>
              <el-button type="danger" size="small" @click="handleDelete(scope)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!--      创建用户面板-->
        <el-dialog
          :title="dialogTitle[dialogType]"
          :visible.sync="dialogVisible"
          :close-on-click-modal=false
          top="5vh">

          <el-form
            ref=""
            :model="temper"
            :rules="rules"
            label-width="100px"
            style=" width: 80%; margin-left:50px;">
            <el-form-item label="组织架构：" prop="account">
              <el-input
                placeholder="请输入内容"
                v-model="tempOrganize.tenant_name"
                :disabled="true">
              </el-input>
            </el-form-item>

            <el-form-item label="年级：" prop="order">
              <el-select v-model="temper.kcode" @change="selectGrade" placeholder="请选择年级" style="width: 100%">
                <el-option v-for="(item,index) in GRADE_SYS"
                           :label="item.label"
                           :value="item.kcode"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="绑定教室：" prop="">
              <el-select v-model="temper.room_code" @change="selectGrade" placeholder="请选择教室" style="width: 100%">
                <el-option v-for="(item,index) in GRADE_SYS"
                           :label="item.label"
                           :value="item.kcode"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <!--            <el-form-item label="创建班级：" prop="describe">-->
            <!--              <el-input-number v-model="temper.classnum" @change="handleChange_addClassNum" :min="0"-->
            <!--                               label="描述文字"></el-input-number>-->
            <!--            </el-form-item>-->
            <!--            <el-form-item-->
            <!--              v-for="(domain, index) in dynamicValidateForm.domains"-->
            <!--              :label="'域名' + index"-->
            <!--              :key="domain.key"-->
            <!--              :prop="'domains.' + index + '.value'"-->
            <!--              :rules="{-->
            <!--      required: true, message: '域名不能为空', trigger: 'blur'-->
            <!--    }"-->
            <!--            >-->
            <!--              <el-input v-model="domain.value"></el-input><el-button @click.prevent="removeDomain(domain)">删除</el-button>-->

            <!--            </el-form-item>-->

            <el-form-item label="描述：" prop="describe">
              <!--              <el-input v-model.number="defaultOrder.describe"></el-input>-->
              <el-input
                type="textarea"
                :rows="2"
                placeholder="请输入内容"
                v-model="temper.description"
                maxlength="30"
                show-word-limit>
              </el-input>
            </el-form-item>


            <!--            <el-form-item label="绑定班级：">-->
            <!--              <el-tree-->
            <!--                ref="tree"-->
            <!--                :check-strictly="true"-->
            <!--                :data="classList"-->
            <!--                show-checkbox-->
            <!--                node-key="path"-->
            <!--                class="permission-tree"-->
            <!--              />-->
            <!--            </el-form-item>-->


            <el-form-item>
              <div style="text-align:right;">
                <el-button type="danger" @click="cancelConsumer">取消</el-button>
                <el-button type="primary" @click="confirmConsumer(dialogType)">确认</el-button>
              </div>
            </el-form-item>
          </el-form>

        </el-dialog>
      </el-main>

    </el-container>
  </div>
</template>

<script>
  import { deepClone } from '@/utils'
  import { getGrades, addGrade, updateGrade, deleteGrade } from '@/api/grade'
  import { findObjByProp } from '@/utils/utilc'

  const defaultClass = {
    id: '',
    kcode: '',//班级编码（唯一）规则：组织架构code+
    label: '',//对外显示名称
    grade_code: '',//年级编码
    organize_code: '',//组织架构code
    room_code: '',//教室编码，对应摄像头
    description: ''
  }

  /***
   * 班级信息(从华栖云获取数据)
   * @type {{room_code: string, id: string}}
   */
  const defaultRoom ={
    id:'',
    kcode: '',
    label:''

  }
  export default {
    name: 'index',

    data() {
      return {
        rules: {
          // account:[{ required: true, message: '请选择套餐', trigger: 'blur' }],
          // passwd:[{ required: true, message: '请选择套餐', trigger: 'blur' }],
          // tel:[{ required: true, message: '请选择套餐', trigger: 'blur' }],
          // role:[{ required: true, message: '不能为空', trigger: 'blur' }],
        },
        input_toolbar: '',
        tempOrganize: this.$global.ORGANIZELIST[0],
        dialogTitle: ['创建', '编辑'],
        temper: Object.assign({}, defaultClass),
        temperList: [],
        GRADE_SYS: [],
        organizeList: this.$global.ORGANIZELIST,
        dialogVisible: false,
        dialogType: '0',
        roomList: []

      }
    },

    computed: {},

    created() {
      // Mock: get all routes and roles list from server
      this.getGrades()
      this.temper.organize_code = this.tempOrganize.tenant_id
    },

    methods: {

      onSearch() {
      },
      onCreate() {
        this.dialogVisible = true
        this.$nextTick(() => {
          this.temper = Object.assign({}, defaultClass)
          this.temper.organize_code = this.tempOrganize.tenant_id
        })

      },

      async getGrades() {

        const res = await getGrades(this.tempOrganize.tenant_id)
        this.temperList = res.data

        this.GRADE_SYS = await this.$global.GRADE_SYS()

        // console.log('======' + JSON.stringify(this.GRADE_SYS))

      },

      cancelConsumer() {
        this.dialogVisible = false
      },

      async confirmConsumer(type) {

        if (type == 0) {//创建

          //生成班级编码


          const { data } = await addGrade(this.temper)
          this.temper.id = data.id
          // this.temper.kcode = data.kcode
          console.log('创建==' + JSON.stringify(this.temper))
          this.temperList.push(this.temper)
        } else {//edit
          await updateGrade(this.temper)
          for (let index = 0; index < this.temperList.length; index++) {
            if (this.temperList[index].id === this.temper.id) {
              this.temperList.splice(index, 1, Object.assign({}, this.temper))
              break
            }
          }
        }

        this.cancelConsumer()
      },

      handleAddConsumer() {
        this.temper = Object.assign({}, defaultClass)
        if (this.$refs.tree) {
          this.$refs.tree.setCheckedNodes([])
        }
        this.dialogType = '0'
        this.dialogVisible = true
      },
      handleEdit(scope) {
        this.dialogType = '1'
        this.dialogVisible = true
        this.temper = deepClone(scope.row)
        this.$nextTick(() => {
        })
      },
      handleDelete({ $index, row }) {
        this.$confirm('确定要删除年级吗?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async() => {
            await deleteGrade(row.id)
            this.temperList.splice($index, 1)
            this.$message({
              type: 'success',
              message: 'Delete succed !'
            })
          })
          .catch(err => {
            console.error(err)
          })
      },

      handleChange_addClassNum(value) {
        // this.temper.classnum = value
        console.log('handleChange_addClassNum==' + value + '==' + this.temper.classnum)
      },

      selectGrade(value) {

        this.temper.name = findObjByProp('kcode', value, this.GRADE_SYS).label

      }

    }

  }
</script>

<style scoped>

  .underInputWords {
    font-size: small;
    color: #999 !important;
    padding: 0 5px !important
  }


</style>
<style>
  .el-table th {
    display: table-cell !important;
  }
</style>
